################################################################################
# SharePoint 2010 - AutoDeploy
# Created By Nate Bruneau | MSIT
#
################################################################################

################################################################################
# Format:
# .\autodeploy.ps1 <EnvironmentName> {-pre,-main,-post}
#  or
# .\autodeploy.ps1 -Path <PathtoEnvParam.ps1> {-pre,-main,-post}
################################################################################

param([String]$ConfigFile,[String]$Stage)
Clear-Host
$envpath = $null
$env:terminate = $false

#REGION ConfigVars
# Fairly static variables used for runtime, such as build scripts location, etc
$env:SPAutoFolder = "\\natehomepc\spcontent\SPAuto"
$EnvFolder = "$env:SPAutoFolder\Env\"
$LibraryPath = $env:SPAutoFolder

if ($Logging -eq ""){
$env:Logging = $true
} else {
$env:Logging = $Logging
}
#ENDREGION ConfigVars

#REGION Functions
#Keep your functions all up in here
################################################################################
# Displays correct command syntax
################################################################################
function HelpMessage {
	Write-Host -ForegroundColor Yellow "########### O14 AutoDeploy Tool ###########"
	Write-Host -ForegroundColor Yellow "Format:"
	Write-Host -ForegroundColor Yellow ".\autodeploy.ps1 -ConfigFile <EnvironmentName> -Stage (pre | main | post | link)"
	Write-Host -ForegroundColor Yellow "or"
	Write-Host -ForegroundColor Yellow ".\autodeploy.ps1 -ConfigFile <PathtoEnvParam.ps1> -Stage (pre | main | post | link)"
	Write-Host -ForegroundColor Yellow "###########################################"
	Exit 1
}

################################################################################
# Verifies that the farm service account exists in AD
################################################################################
function validateUserAD([String] $domain, [String] $user, [String] $pass){

	Trap [Exception] { Write-Host -ForegroundColor Red "Incorrect Password for $env:serviceacct"; return $false}

	$entry = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$domain", $user, $pass)
	$MySearcher = New-Object System.DirectoryServices.DirectorySearcher($entry)
	$mySearcher.Filter = ("cn=$user")
	$results = $mySearcher.FindAll()
	return $true
}

################################################################################
# Gets the farm service account password from the user executing the script so 
# we don't keep our farm service account password in plaintext for the leet 
# haxors
################################################################################
function SetPass([String] $farmpass){
	
	
	$userdomain = $env:serviceacct.Split("\")
	
	$farmdomain = $userdomain[0]
	$farmuser = $userdomain[1]
	
	if (validateUserAD $farmdomain $farmuser $farmpass){
	## if pass - continue, if error: quit with exception
	$env:serviceacctpwd=$farmpass		

	} else {
	# if user could not be validated exit
	exit 1
	}
}

function LoadPass(){

	$farmpass = Read-Host "Please Type in the password for $env:serviceacct"
	SetPass $farmpass

}


################################################################################
# Attempts to load the supplied config file. If it can't it errors. Also
# if there were parameters supplied at the command line, this is where they 
# override the values supplied in the config file
################################################################################
function LoadConfigFile {
	if ($ConfigFile){
		if(!$ConfigFile.EndsWith("ps1")) {
			$ConfigFile = $ConfigFile + ".ps1"
		}
		Write-Host -NoNewline -ForegroundColor White "Loading Config File: " 
		write-host -NoNewline -ForegroundColor DarkGray $EnvFolder
		Write-Host -ForegroundColor Green $ConfigFile
		
		if(Test-Path $ConfigFile) {
			& $ConfigFile
			LoadPass
		}
		elseif (Test-Path $EnvFolder$ConfigFile) {
			& $EnvFolder$ConfigFile
			LoadPass
		}
		else {
			Write-Host -ForegroundColor Red "Loading Config File failed. Please make sure the file exists in the path."
			exit 1
		}
	}
}

function ExecuteStage {
	if ($Stage -eq "pre"){
		Write-Host -ForegroundColor Yellow "Executing Pre Req Scripts..."
		$prePath = "$LibraryPath\Pre\Pre.ps1"
		& $prePath
	}
	elseif ($Stage -eq "main"){
		Write-Host -ForegroundColor Yellow "Executing Main Install Scripts..."
		$mainPath = "$LibraryPath\Main\Main.ps1"
		& $mainPath
	}
	elseif ($Stage -eq "post"){
		Write-Host -ForegroundColor Yellow "Executing Post Config Scripts..."
		$postPath = "$LibraryPath\Post\Post.ps1"
		& $postPath
	}
	elseif ($Stage -eq "link"){
		Write-Host -ForegroundColor Green "Linking Variables to $env:farmname completed."
	}
}
#ENDREGION Functions

#REGION ParameterValidation


# Whether or not any params are missing
[Bool]$AreMissingParams = $false
# For tracking the missing params
$MissingParams = @()

# Checks to see if the $ConfigFile param has been set
if(!$ConfigFile) {
	# If so, flags missing params
	$AreMissingParams = $true
	# Adds missing params to array
	$MissingParams = $MissingParams + "Missing -ConfigFile parameter"
}
else {
	# If it is there, satiate overpowering OCD
	$ConfigFile = $ConfigFile.ToLower()
}

# Checks to see if the $ConfigFile param has been set
if(!$Stage) {
	# If so, flags missing params
	$AreMissingParams = $true
	# Adds missing params to array
	$MissingParams = $MissingParams + "Missing -Stage parameter"
}
else {
	# If it is there, satiate overpowering OCD
	# Should probably also check to make sure it's a valid stage
	$Stage = $Stage.ToLower()
	switch($Stage) {
		"pre" { Write-Host "Requested stage is Pre..." }
		"main" { Write-Host "Requested stage is Main..." }
		"post" { Write-Host "Requested stage is Post..." }
		default { Write-Host "Invalid stage" }
	}
}

# If there are missing params, spits out the missing ones to console
if($AreMissingParams) {
	Write-Host
	foreach($ErrMsg in $MissingParams) {
		Write-Host $ErrMsg
	}
	Write-Host
	# Then tells you the correct syntax
	HelpMessage
}

#ENDREGION ParameterValidation

#REGION Main
# The meat, the engine, the vroom vroom
LoadConfigFile
ExecuteStage
#ENDREGION Main
